//
//  BaseWebController.m
//  Rail
//
//  Created by hychen on 2018/3/1.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "BaseWebController.h"

@interface BaseWebController ()<YCWebViewDelegate>

@end

@implementation BaseWebController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.navTitle;
    self.navigationItem.titleView.tintColor = kWhiteColor;
    [self prepareWebView];
    
    [self loadUrlString:self.url];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareWebView {
    // 初始化
    _webView = [[YCWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetHeight(self.view.bounds)-[BMUtility statusBarAndNavBarHeight])];
    // 代理
    _webView.delegate = self;
    // 显示进度条
    _webView.displayProgressBar = YES;
    // 允许侧滑返回
    _webView.allowsBackForwardNavigationGestures = YES;
    self.webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    [self.view addSubview:self.webView];
}

- (void)refreshData{
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
}

- (void)loadUrlString:(NSString *)string{
    NSURL *url = [NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

#pragma mark - UIWebView Delegate
- (BOOL)webView:(YCWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(WKNavigationType)navigationType {
    NSLog(@"跳转链接:%@",webView.URL.absoluteString);
    NSString *urlString = webView.URL.absoluteString;
    
    //deepLink
    if ([WebHelper ProcessDeepLinkWithUrl:urlString?:@"" vc:self]) {
        return NO;
    }
    
    return YES;
}

- (void)webView:(YCWebView *)webView didFailLoadWithError:(NSError *)error {
    [self.webView.scrollView.mj_header endRefreshing];
}

- (void)webViewDidStartLoad:(YCWebView *)webView {
    NSString *urlString = webView.URL.absoluteString;
    
    //deepLink
    if ([WebHelper ProcessDeepLinkWithUrl:urlString?:@"" vc:self]) {
        [webView stopLoading];
    }
}

- (void)webViewDidFinishLoad:(YCWebView *)webView {
    [self.webView.scrollView.mj_header endRefreshing];
    
}

// 网页加载进度
- (void)webView:(YCWebView *)webView estimatedProgress:(CGFloat)progress
{
//    NSLog(@"%f",progress);
}

// 网页标题更新
- (void)webView:(YCWebView *)webView didUpdateTitle:(NSString *)title
{
    self.title = title;
}
@end
